<#import "PageTemplate.ftl" as p> 

<@p.page>
<div class="page-header">
	<h1>Create and Run Job</h1>
</div>
<p class="lead">Please input all the data required to create and run a Job.</class>

<div class="input-group"><span class="input-group-addon">Label: </span><input id="label" type="text" class="form-control" placeholder="Label" value=""></input></div>
<br />
<div class="input-group"><span class="input-group-addon">Description: </span><textarea id="description" class="form-control" placeholder="Description of the Job" rows="5"></textarea></div>
<br />	
<div class="input-group"><span class="input-group-addon">Input Data:<br /><br /><small>(in Turtle/N3)</small></span><textarea id="inputData" class="form-control" placeholder="Input Data" rows="20">
@prefix rdf:        &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; .
@prefix rdfs:       &lt;http://www.w3.org/2000/01/rdf-schema#&gt; .
@prefix owl:        &lt;http://www.w3.org/2002/07/owl#&gt; .
@prefix cflow:		&lt;http://compflow.pt/flowOntology/&gt; .
</textarea></div>

<div class="page-header">
	<button id="addWorkflowButton" class="btn btn-default pull-right" type="submit"><span class="glyphicon glyphicon-plus"></span>  Add Workflow</button>
	<h2>Workflows</h2>
	<input id="workflowCount" type="hidden" value="0"></input>
</div>
<p class="lead">Specify all the workflows that must be started inside this job. If the imported ontologies are not available online at the specified URIs, please add them here.</class>

<div id="workflowDiv">
</div>
 	  
<p><button id="createAndRunButton" class="btn btn-lg btn-primary btn-block" type="submit">Create and Run Job</button></p>

<script>
$(document).ready(function() {
	var removeWorkflowFunc = function(event) {
		event.preventDefault();
		var count = $('#workflowCount');
		var len = parseInt(count.val());
		count.val(len - 1);
		
		var orig = parseInt($(this).val());
		
		$('#workflow' + orig).remove();
		
		for(var i=orig+1;i<len;i++) {
			$('#workflow' + i).attr('id', 'workflow' + (i-1));
			$('#removeWorkflowButton' + i).attr('id', 'removeWorkflowButton' + (i-1)).attr('value', (i-1));
			$('#workflowOntology' + i).attr('id', 'workflowOntology' + (i-1));
			$('#workflowClass' + i).attr('id', 'workflowClass' + (i-1));
		}
	};
	
	var addOntologyImportFunc = function(event) {
		event.preventDefault();
		
		var workflowIndex = parseInt($(this).val());
		
		var count = $('#ontologyImportCount' + workflowIndex);
		var i = parseInt(count.val());
		count.val(i + 1);
		
		var div = $('#ontologyImportDiv' + workflowIndex);
		
		var importDiv = $('<div>', {id: 'ontologyImport' + workflowIndex + '_' + i});
		var ontologyDiv = $('<div>', {class: 'input-group'});
	    ontologyDiv.html('<span class="input-group-addon">Workflow-Def. Ontology Import (Local File): </span><input id="workflowOntologyImport' + workflowIndex + '_' + i + '" type="file" class="form-control" placeholder="Workflow-Definition Ontology Import URI" value=""></input>');
	    ontologyDiv.append(' <span class="input-group-btn"><button id="removeOntologyImport' + workflowIndex + '_' + i +'" class="btn btn-default pull-right" type="submit" value="' + workflowIndex + '_' + i + '"><span class="glyphicon glyphicon-minus"></span></button></span>');
	    ontologyDiv.find('button').click(removeOntologyImportFunc);
	    importDiv.append('<br />');
	    importDiv.append(ontologyDiv);
	    
	    div.append(importDiv);
	};
	
	var removeOntologyImportFunc = function(event) {
		event.preventDefault();
		
		var values = $(this).val();
		var workflowIndex = parseInt(values.split("_")[0]);
		var importIndex = parseInt(values.split("_")[1]);
		
		var count = $('#ontologyImportCount' + workflowIndex);
		var len = parseInt(count.val());
		count.val(len - 1);
				
		$('#ontologyImport' + values).remove();
		
		for(var i=importIndex+1;i<len;i++) {
			$('#ontologyImport' + workflowIndex + '_' + i).attr('id', 'ontologyImport' + workflowIndex + '_' + (i-1));
			$('#workflowOntologyImport' + workflowIndex + '_' + i).attr('id', 'workflowOntologyImport' + workflowIndex + '_' + (i-1));
			$('#removeOntologyImport' + workflowIndex + '_' + i).attr('id', 'removeOntologyImport' + workflowIndex + '_' + (i-1)).attr('value', workflowIndex + '_' + (i-1));
		}
	};
	
	var readFile = function (file, workflowIndex, importIndex) {
	    var reader = new FileReader();
	    var deferred = $.Deferred();
	 
	    reader.onload = function(event) {
	        deferred.resolve({ result: event.target.result, workflowIndex: workflowIndex, importIndex: importIndex });
	    };
	 
	    reader.onerror = function() {
	        deferred.reject({ obj: this, workflowIndex: workflowIndex, importIndex: importIndex });
	    };
	 
	    reader.readAsText(file);
	 
	    return deferred.promise();
	};

	$("#addWorkflowButton").click(function (event) {
	    if(event) event.preventDefault();
	    
	    var div = $('#workflowDiv');
	    var count = $('#workflowCount');
	    var i = parseInt(count.val());
	    count.val(i + 1);
	    
	    var rootDiv = $('<div>', {id: 'workflow' + i, class: 'panel panel-default'});
	   
	    var bodyDiv = $('<div>', {class: 'panel-body'});
	    rootDiv.append(bodyDiv);
	    
	    var buttonDiv = $('<div>');
	    if(i > 0) buttonDiv.html('<button id="removeWorkflowButton' + i + '" class="btn btn-default" type="submit" value="' + i + '"><span class="glyphicon glyphicon-minus"></span>  Remove Workflow</button>');
	    buttonDiv.html(buttonDiv.html() + ' <button id="addOntologyImportButton' + i + '" class="btn btn-default" type="submit" value="' + i + '"><span class="glyphicon glyphicon-import"></span>  Add Ontology Import</button>');
	    buttonDiv.html(buttonDiv.html() + ' <input id="ontologyImportCount' + i + '" type="hidden" value="0"></input>');
	    if(i > 0) buttonDiv.find('button#removeWorkflowButton' + i).click(removeWorkflowFunc);
	    buttonDiv.find('button#addOntologyImportButton' + i).click(addOntologyImportFunc);
	    bodyDiv.append(buttonDiv);
	    bodyDiv.append($('<br>'));
	    
	    var classDiv = $('<div>', {class: 'input-group'});
	    classDiv.html('<span class="input-group-addon">Workflow-Def. Class (URI): </span><input id="workflowClass' + i + '" type="text" class="form-control" placeholder="Workflow-Definition Class URI (sub-class of \'Workflow\')" value=""></input>');
	    bodyDiv.append(classDiv);
	    bodyDiv.append($('<br>'));
	    
	    var ontologyDiv = $('<div>', {class: 'input-group'});
	    ontologyDiv.html('<span class="input-group-addon">Workflow-Def. Ontology (Local File): </span><input id="workflowOntology' + i + '" type="file" class="form-control" placeholder="Workflow-Definition Ontology URI" value=""></input>');
	    bodyDiv.append(ontologyDiv);
	    
	    var importDiv = $('<div>', {id: 'ontologyImportDiv' + i});
	    bodyDiv.append(importDiv);
	    
	    div.append(rootDiv);	    
	});
	$("#addWorkflowButton").click();
	
	$('#createAndRunButton').click(function(event) {
		event.preventDefault();
		$('.alert-error').hide();
		$('#progress').show();
		
		var data = { 
			label: $('#label').val(), 
			description: $('#description').val(), 
			inputData: $('#inputData').val(),
			workflows: []
		}
		
		var promises = [];
		var len = parseInt($('#workflowCount').val());
		for(var i=0; i<len; i++) {
			var workflowOntologyFile = $('#workflowOntology' + i)[0].files[0];
			// if(workflowOntologyPath.indexOf('file:') == 0)
			promises.push(readFile(workflowOntologyFile, i, -1));
				
			data.workflows[i] = {
				ontology: workflowOntologyFile.name,
				format: workflowOntologyFile.name.slice(workflowOntologyFile.name.lastIndexOf('.')+1).toUpperCase(),
				imports: [],
				class: $('#workflowClass' + i).val()
			};
			
			var len2 = parseInt($('#ontologyImportCount' + i).val());
			for(var j=0; j<len2; j++) {
				var importFile = $('#workflowOntologyImport' + i + '_' + j)[0].files[0];
				data.workflows[i].imports[j] = { format: importFile.name.slice(importFile.name.lastIndexOf('.')+1).toUpperCase() };
				promises.push(readFile(importFile, i, j));
			}
		}
		
		if(promises.length == 0) promises[0] = {};
		$.when.apply($, promises).done(function() {
			for(var i=0;i<arguments.length;i++) {
				var arg = arguments[i];
				if(arg.importIndex >= 0) data.workflows[arg.workflowIndex].imports[arg.importIndex].ontology = arg.result;
				else data.workflows[arg.workflowIndex].ontology = arg.result;
			}
						
			$.ajax({
	            url: '/api/job',
	            type:'POST',
	            accepts : "application/json",
	    		contentType : "application/json",
	    		processData : false,
	    		dataType : "text",
	            data: JSON.stringify(data),
	            success: function (data) {
	            	window.location.href="/job";// + data;
	            },
	            error: function(data) {
	            	var msg = "Server error " + data.status + ". Please try again later.";
	            	if(data.status == 400)
	            		msg = "Invalid input data.";
	            	
	            	$('#progress').hide();
	            	 $('.alert-error').text(msg).show();
	            }
	        });
		}).fail(function() {
			$('#progress').hide();
			$('.alert-error').text('Failed to read one or more of the ontology files.').show();
		});
		
	});
});
</script>
</@p.page>